import Flyio from './wx';
import baseUrl from './baseUrlConfig';
import api from './api';
import qs from './qs';

const fly = new Flyio;
fly.config.timeout = baseUrl.APITimeout;
fly.config.baseURL = baseUrl.API;
fly.config.headers = {
  'content-type': 'application/json'
};

fly.interceptors.request.use(
  request => {
    let token = wx.getStorageSync('token');
    if (token) {
      request.headers['token'] = token;
    }
    return request;
  },
  err => {
    return Promise.reject(error);
  }
);

fly.interceptors.response.use(
  async response => {
    const data = response.data;
    if (typeof data === 'string') {
      return { code: 200, msg: 'toJson', data: data };
    }
    return data;
  },
  err => {
    return Promise.reject(
      typeof err === 'object' && err.message
        ? err.message
        : 'server error'
    );
  }
);

const ajax = async (
  name,
  data = {},
  success,
  fail = () => {}
) => {
  if (!Array.isArray(name)) {
    console.warn('ajaxName:'+name);
    return;
  }

  let url = name[1];
  let type = name[0];
  let res;
  console.log(`API | ${type}: ` + url, data);
  if (typeof success === 'function') {
    res = await fly
    .request(url, data, {
      method: type
    })
    .then(success)
    .catch(fail);
  } else {
    res = await fly.request(url, data, {
      method: type
    }).then((result) => {
      //如果未登录需要自动转跳到登录界面
      if (result.Tag === 211) {
        goLogin();
      }
      return result
    });
  }

  return res;
};
// 转跳登录界面
const goLogin = () => {
  wx.redirectTo({
    url: '/pages/login/login',
  })
}

const wxLogin = async () => {
  return await new Promise((resolve, reject) => {
    wx.login({
      success (res) {
        if (res.code) {
          resolve(res.code);
        }
      }
    });
  });
};

let newFly = new Flyio;

export default {
  fly:fly,
  ajax:ajax,
  async checkSession() {
    console.log("checkSession");
    let token = wx.getStorageSync('token');
    if (!token) {
      await goLogin();
    } else {
      // 本地还没获取过用户信息，需要保证 session_key 有效期
      wx.checkSession({
        async success() {
          console.log("session_key 未过期");
        },
        async fail() {
          console.warn("session_key 已经失效");
          await goLogin();
        }
      });
    }
  },
  async getInfo(app){
    ajax(api.GetInfo,{
      mid:app.globalData.mid
    }).then((val) => {
      if (val.Tag == 1 && val.Data.appname) {
        this.setTitle(val.Data.appname);

        app.globalData.mTitle = val.Data.appname;
        app.globalData.mid = app.globalData.mid ? app.globalData.mid : val.Data.appid;
      }else if(val.Tag == 0 || val.Tag == 211){
        wx.setStorageSync('token', '');
      }
    }).catch((val) => {
      // wx.setNavigationBarTitle({
      //   title: 'title',
      // });
    });
  },
  setTitle(name){
    wx.setNavigationBarTitle({
      title: name,
    });
  },
  updateMyTitle(app){
    if (!app.globalData.mTitle) {
      this.getInfo(app);
    } else {
      this.setTitle(app.globalData.mTitle);
    }
  }
};